# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import time
import utils.pgsql.base.pgconn as pgconn
import json

"""
template management
add 
delete
modify
...
"""
_tblName = 'tbl_template'

_DB_SCRIPT = f"""
CREATE TABLE IF NOT EXISTS {_tblName} (
                "templateId"  SERIAL PRIMARY KEY ,    
                "templateCloudId" VARCHAR(260) NOT NULL default '',     
                "bgmName" VARCHAR(260) NOT NULL default '',             
                "operatorId" INTEGER NOT NULL default 0,                
                "caseId" INTEGER NOT NULL default 0,                    
                "templateName"  VARCHAR(260) NOT NULL default '' ,       
                "faceNum" INTEGER NOT NULL default 0,                    
                "templateData"  VARCHAR(4096) NOT NULL default '',  
                "note" VARCHAR(260) NOT NULL default '',        
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default '',
                "ticketPrice" INTEGER NOT NULL default 0
                );
                """


class PgTemplate:

    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

    def addTemplate(self, dic) -> dict:
        dic['createTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        dic['updateTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        if 'templateData' in dic:
            dic['templateData'] = json.dumps(dic['templateData'])
        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

  
        sql = "insert into {} ({}) values ({}) ".format(_tblName, sql_key, sql_val[:-1])
        print("sql",sql)
        return self._pgConn.exec(sql)

 
    def templateNameget(self, templateName,caseId) -> list:
        sql = "select \"templateName\" from {}  where  \"templateName\" = \'{}\' and \"caseId\" = \'{}\' ".format(
            _tblName, templateName,caseId)
        return self._pgConn.exec_fetchall(sql)
    
 
    def templateNameeditget(self, templateName,caseId,templateId) -> list:
        sql = "select * from {}  where  \"templateName\" = \'{}\' and \"caseId\" = \'{}\' and \"templateId\" != \'{}\' ".format(
            _tblName, templateName,caseId,templateId)
        return self._pgConn.exec_fetchall(sql)
    
 
    def templatmodify(self, ids, dic) -> bool:
        dic['updateTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        if 'templateData' in dic:
            dic['templateData'] = json.dumps(dic['templateData'])

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])   + " \"templateId\" = \'{}\' ".format(ids)
        # 修改模板的时候，要同步把 synState 字段从1改成0，该字段出现在 tbl_activity 表里.
        tmp = self._pgConn.exec(sql)
        reset_sql = f'UPDATE "public"."tbl_activity" set "synState" =\'0\' WHERE "templateId" = \'{ids}\';'
        self._pgConn.exec(reset_sql)
        return tmp
    
  
    def modify(self, ids, dic) -> bool:
        dic['updateTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        if 'templateData' in dic:
            dic['templateData'] = json.dumps(dic['templateData'])

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"pointId\" = \'{}\' ".format(ids)
        return self._pgConn.exec(sql)

  
    def delete(self, ids) -> bool:
        sql = "delete from {} where \"templateId\" = \'{}\' ".format(
            _tblName, ids)
        return self._pgConn.exec(sql)

 
    def get(self, ids) -> dict:
        sql = "select * from {} where \"templateId\" = \'{}\' ".format(
            _tblName, ids)
        return self._pgConn.exec_fetchone(sql)

    def all(self) -> list:
        sql = "select a.*,n.\"caseName\" from {} a left Join tbl_case n on a.\"caseId\"=n.\"caseId\" where n.\"dataValid\" !=0 order by a.\"templateId\"".format(
            _tblName)
        return self._pgConn.exec_fetchall(sql)

    def allByOperatorId(self, operatorId) -> list:
        sql = "select a.*,n.\"caseName\" from {} a left Join tbl_case n on a.\"caseId\"=n.\"caseId\" where n.\"dataValid\" !=0 and a.\"operatorId\" = \'{}\' order by a.\"templateId\"" .format(
            _tblName, operatorId)
        return self._pgConn.exec_fetchall(sql)

    def allByCaseId(self, caseId, limit="") -> list:
        tmp = f' and a."templateName" SIMILAR TO \'%({limit})%\' ' if limit else ""
        sql = "select a.*,n.\"caseName\" from {} a left Join tbl_case n on a.\"caseId\"=n.\"caseId\" where n.\"dataValid\" != 0 and a.\"caseId\" = \'{}\' {} order by a.\"templateId\"" .format(
            _tblName, caseId, tmp)
        return self._pgConn.exec_fetchall(sql)

    def select_template_onecaseID_notsyn(self,caseId) -> list:
        sql = "select * from {} where \"synState\" = 0 and \"caseId\" = \'{}\'".format(
            _tblName,caseId)
        print(sql)
        return self._pgConn.exec_fetchall(sql)

    def select_template_notsyn(self) -> list:
        sql = "select * from {} where \"synState\" = 0".format(
            _tblName)
        print(sql)
        return self._pgConn.exec_fetchall(sql)

    # 根据模板id 查询模板数据
    def get_templateId_data(self, templateId) -> dict:
        sql = "select * from {} where \"templateId\" = \'{}\' ".format(
            _tblName, templateId)
        # print("get_templateId_data:",sql)
        return self._pgConn.exec_fetchone(sql)

    def sync_playground(self):
        tmp = self.all()
        for i in tmp:
            sql = ''
